package com.bjpowernode.other.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁超时
 */
public class Lock02 {

    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(()->{m1();}).start();
        new Thread(()->{m1();}).start();
    }

    public static void m1() {

        try {
            //尝试获取锁
            boolean flag = lock.tryLock(3, TimeUnit.SECONDS);
            if (flag) {
                //获取到锁
                System.out.println(Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(4);
            } else {
                System.out.println(Thread.currentThread().getName() + "获取锁失败");
            }

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //判断当前线程是否持有锁，若持有锁，则释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
